/* 
 * File:   image.c
 * Author: bjorn
 * Ultra-thin "wraper" around SDL image pointers
 * Created on September 4, 2007, 10:56 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

#include "image.h"
#include "rope.h"

int image_wide(Image self) {
    return self->w;
} 

int image_high(Image self) {
    return self->h;
} 

Image image_load_c(const char * filename) {
    return IMG_Load(filename);
}

Image image_load(Rope filename) {
    return image_load_c(filename.c_str());
}


Image image_free(Image self) {
    if(self) { SDL_FreeSurface(self); }
    return NULL;
}

Image image_fill_all(Image self, int r, int g, int b ) {
    SDL_FillRect(self, NULL, SDL_MapRGB(self->format, r, g, b));
    return self;
}

Image image_fill_all_alpha(Image self, int r, int g, int b, int a ) {
    SDL_FillRect(self, NULL, SDL_MapRGBA(self->format, r, g, b, a));
    return self;
}


Image image_blit_size(Image target, int tar_x, int tar_y, Image source, 
        int src_x, int src_y, int src_w, int src_h  ) 
{
    SDL_Rect source_rect, target_rect;
    source_rect.x = src_x;
    source_rect.y = src_y;
    source_rect.w = src_w;
    source_rect.h = src_h;
    target_rect.x = tar_x;
    target_rect.y = tar_y;
    SDL_BlitSurface(source, &source_rect, target, &target_rect);
    return target;
}

Image image_blit(Image target, int tar_x, int tar_y, Image source ) 
{
    SDL_Rect source_rect, target_rect;
    source_rect.x = 0;
    source_rect.y = 0;
    source_rect.w = image_wide(source);;
    source_rect.h = image_high(source);
    target_rect.x = tar_x;
    target_rect.y = tar_y;
    SDL_BlitSurface(source, &source_rect, target, &target_rect);
    return target;
}

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    #define RMASK 0xff000000
    #define GMASK 0x00ff0000
    #define BMASK 0x0000ff00
    #define AMASK 0x000000ff
#else
	#define RMASK 0x000000ff
	#define GMASK 0x0000ff00	
	#define BMASK 0x00ff0000
	#define AMASK 0xff000000
#endif

/* Makes a 32 bit image with the specified dimensions. 
If alpha is true, the image will support transparency. 
Otherwise it will have a colour key.   
*/
Image image_make(int wide, int high, bool alpha) {
	Uint32 flags = SDL_SWSURFACE ;
	if (alpha) { flags = flags | SDL_SRCALPHA; } 
	else { flags = flags | SDL_SRCCOLORKEY; }
	return SDL_CreateRGBSurface(flags, wide, high, 32, RMASK, GMASK, BMASK, AMASK);
}
